#include <my_header.h>

/* Usage: ./1_AUser_select */
int main(int argc, char *argv[]){                                  
    int fd_write = open("write.pipe", O_WRONLY);
    int fd_read = open("read.pipe", O_RDONLY);
    ERROR_CHECK(fd_write, -1, "open write");
    ERROR_CHECK(fd_read, -1, "open read");

    char buf[60];
    // 监听集合
    // fd_set是一个结构体
    // 存放文件描述符
    fd_set set;

    // 记录BUser发过来信息的时间
    time_t tag_a_msg = time(NULL);
    ERROR_CHECK(tag_a_msg, -1, "time");
    // 记录当前的时间
    time_t tag_cur = time(NULL);
    ERROR_CHECK(tag_cur, -1, "tag_cur");

    while(1)
    {
        //初始化集合
        FD_ZERO(&set);
        // 添加要监听的文件描述符
        FD_SET(STDIN_FILENO, &set); // 输入
        FD_SET(fd_read, &set);  //输出

        // 每1秒就绪一次
        struct timeval time_val;
        time_val.tv_sec = 1;
        time_val.tv_usec = 0;


        // 调用select,监听就绪
        int ret_select = select(10, &set,NULL, NULL,
                                &time_val);
        ERROR_CHECK(ret_select, -1, "select");
        //打印剩余时间
        // printf("tv_sec:%ld\n", time_val.tv_sec);
        // 更新当前时间
        tag_cur = time(NULL);
        // 判断fd_read是否在文件描述符集合汇总
        if(FD_ISSET(fd_read, &set))
        {
            bzero(buf, sizeof(buf));    // 清零
            int read_num = read(fd_read, buf, sizeof(buf));

            if(read_num == 0)
            {
                printf("对方已断开连接\n");
                break;
            }
            printf("UserB: %s", buf);
            // 更新a的发送信息时间
             tag_a_msg = time(NULL);
        }

        if(FD_ISSET(STDIN_FILENO, &set))
        {
            bzero(buf, sizeof(buf));    // 清零
            int read_stdin = read(STDIN_FILENO, buf, sizeof(buf));
            if(read_stdin == 0)
            {
                // 用户按下ctrl+d; 输入文件终止符; 终止标准
                // 输入; read返回0
                break;
            }
            write(fd_write, buf, sizeof(buf));
        }
        // 比较信息时间和当前时间
        if(tag_cur - tag_a_msg >= 10)
        {
            printf("10秒未发送信息\n");
            break;
        }
    }
    

    close(fd_write);
    close(fd_read);
    return 0;
}


